import React, { useRef, useEffect } from 'react';
import { View, Animated, Easing, StyleSheet, ViewStyle } from 'react-native';
import { px2dp } from '~/utils/px2dp';

interface Props {
    isPlaying: boolean;
    style?: ViewStyle;
}

const WaveformAnimation = ({ isPlaying, style }: Props) => {
    const animationValues = useRef([...Array(20)].map(() => new Animated.Value(0))).current;
    const animationRefs = useRef<Animated.CompositeAnimation[] | null>(null);

    useEffect(() => {
        if (isPlaying) {
            startAnimation();
        } else {
            stopAnimation();
        }
    }, [isPlaying]);

    const startAnimation = () => {
        animationRefs.current = animationValues.map((value, index) =>
            Animated.loop(
                Animated.sequence([
                    Animated.delay(index * 100),
                    Animated.timing(value, {
                        toValue: 1,
                        duration: 300,
                        easing: Easing.linear,
                        useNativeDriver: true,
                    }),
                    Animated.timing(value, {
                        toValue: 0,
                        duration: 300,
                        easing: Easing.linear,
                        useNativeDriver: true,
                    }),
                ]),
            ),
        );
        Animated.parallel(animationRefs.current).start();
    };

    const stopAnimation = () => {
        animationRefs.current?.forEach((anim) => anim.stop());
    };

    return (
        <View style={styles.waveform}>
            {animationValues.map((value, index) => (
                <Animated.View
                    key={index}
                    style={[
                        styles.bar,
                        style,
                        {
                            transform: [
                                {
                                    scaleY: value.interpolate({
                                        inputRange: [0, 1],
                                        outputRange: [1, 2],
                                    }),
                                },
                            ],
                        },
                    ]}
                />
            ))}
        </View>
    );
};

const styles = StyleSheet.create({
    waveform: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    bar: {
        width: px2dp(12),
        height: px2dp(32),
        borderRadius: px2dp(12),
        backgroundColor: 'blue',
    },
});

export default WaveformAnimation;
